package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.itheima.common.GetSessionId;
import com.itheima.common.Result;
import com.itheima.pojo.AddressBook;
import com.itheima.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    //请求 URL: http://localhost:8080/addressBook/list
    //请求方法: GET
    @GetMapping("/list")
    public Result lists() {
        Long id = GetSessionId.GetId();

        LambdaQueryWrapper<AddressBook> lqw =new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,id);
        List<AddressBook> list = addressBookService.list(lqw);

        return Result.success(list);
    }

//    请求 URL: http://localhost:8080/addressBook
//    请求方法: POST
    @PostMapping
    public Result addAddress(@RequestBody AddressBook address){
        Long id = GetSessionId.GetId();
        address.setUserId(id);
        addressBookService.save(address);
        return Result.success("添加成功");
    }


//    请求 URL: http://localhost:8080/addressBook/default
//    请求方法: PUT
    //id: "1417414926166769666"
    @PutMapping("/default")
    public Result updateDefaultAdderss(@RequestBody Map<String,String> map){

        String addressId = map.get("id");

        //根据adderssId查询User_id
        AddressBook one = addressBookService.getById(addressId);
        Long userId = one.getUserId();


        //将User_id下的所有地址设为0
        UpdateWrapper<AddressBook> qw = new UpdateWrapper<>();
        qw.set("is_default",0).eq("user_id",userId);
        addressBookService.update(qw);

        //将请求的地址设为默认地址
        one.setIsDefault(1);
        addressBookService.updateById(one);

        return Result.success("修改成功");
    }

//    请求 URL: http://localhost:8080/addressBook/default
//    请求方法: GET

    @GetMapping("/default")
    public Result getDefaultAdderss(){

        Long userId = GetSessionId.GetId();

        LambdaQueryWrapper<AddressBook> lqw =new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,userId).eq(AddressBook::getIsDefault,1);
        AddressBook one = addressBookService.getOne(lqw);

        return Result.success(one);
    }
}

